/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package ActionBar;

import CRUD.MarkerFacadeLocal;
import CRUD.PointFacadeLocal;
import CRUD.RouteFacadeLocal;
import Entity.Marker;
import Entity.MarkerPK;
import Entity.Point;
import Entity.PointPK;
import Entity.Route;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.List;
import javax.ejb.EJB;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

/**
 *
 * @author WinKiQue58
 */
@Stateless
public class PreferenceOptions implements PreferenceOptionsLocal {
    
    @PersistenceContext(unitName = "S3R4_Orcl-ejbPU")
        private EntityManager em;
    
    @EJB private MarkerFacadeLocal markerFacade;
    @EJB private RouteFacadeLocal routeFacade;
    @EJB private PointFacadeLocal pointFacade;  
    
    
    public boolean createMarker( String name, List<Point> list,
            BigInteger idPersonalInfo, BigInteger idBranchEnterprise, BigInteger idEnterprise)
    {
         BigInteger maxID;
        
         Query q= em.createQuery("SELECT MAX(r.idRoute) FROM Route r");
           
          try{
          maxID=(BigInteger)q.getSingleResult();
          }catch (Exception e)
          {
              maxID=new BigInteger("0");
          }
          
          Route route= new Route(maxID.add(new BigInteger("1")), name);
          routeFacade.create(route);
        
         maxID=null;
         Query q1= em.createQuery("SELECT MAX(mkr.markerPK.idMarker) FROM Marker mkr WHERE "
                  + "mkr.markerPK.idPersonalInfo = :A AND "
                  + "mkr.markerPK.idBranchenterprise = :B AND "
                  + "mkr.markerPK.idEnterprise = :C");
          q1.setParameter("A", idPersonalInfo);
          q1.setParameter("B", idBranchEnterprise);
          q1.setParameter("C", idEnterprise);
          
          
          try{
          maxID=(BigInteger)q1.getSingleResult();
          }catch (Exception e)
          {
              maxID=new BigInteger("0");
          }
        MarkerPK mPK=new MarkerPK(maxID.add(new BigInteger("1")), idPersonalInfo, idBranchEnterprise, idEnterprise);
        Marker marker=new Marker(mPK, route);
        
        for (Point element : list) {
            maxID=null;
            Query q3= em.createQuery("SELECT MAX(p.pointPK.idPoint) FROM Point p");
             try{
              maxID=(BigInteger)q3.getSingleResult();
              }catch (Exception e)
              {
                  maxID=new BigInteger("0");
              }

            PointPK pPK=new PointPK(maxID.add(new BigInteger("1")), route.getIdRoute()) ;
            Point p=new Point(pPK);
            p.setLatitude(element.getLatitude());
            p.setLongitude(element.getLongitude());
            p.setAddressname(element.getAddressname());
            pointFacade.create(p);
        }
        return true;
    }
    
}
